package client.user.button;

import client.common.dto.AdminUpdateDTO;
import client.common.result.Result;
import client.user.UserArchiveQuery;
import client.user.UserEditDialog;
import remote.service.UserService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
    
    private JButton button;
    private JTable table;
    private int row;
    private boolean isEdit;
    private UserService userService = new UserService() {
    }; // 使用用户服务
    
    public ButtonEditor(JTable table, boolean isEdit) {
        this.table = table;
        this.isEdit = isEdit;
        button = new JButton(isEdit ? "修改" : "删除");
        button.addActionListener(this);
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        this.row = row;
        button.setText(isEdit ? "修改" : "删除"); // 更新按钮文本
        return button;
    }
    
    @Override
    public Object getCellEditorValue() {
        return isEdit ? "修改" : "删除";
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        fireEditingStopped(); // 停止编辑
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        
        // 获取数据库中的 ID 号并转换为 Long
        String userId = String.valueOf(model.getValueAt(row, 0).toString());
        if (isEdit) {
            // 获取当前行的其他数据
            String phoneNumber = model.getValueAt(row, 1).toString();
            String identity = model.getValueAt(row, 2).toString();
            String realName = model.getValueAt(row, 3).toString();
            String gender = model.getValueAt(row, 4).toString();
            String address = model.getValueAt(row, 5).toString();
            String birth = model.getValueAt(row, 6).toString();
            handleEdit(userId, phoneNumber, identity, realName, gender, address, birth);
        } else {
            handleDelete(userId);
        }
    }
    
    private void handleEdit(String userId, String phoneNumber, String identity, String realName, String gender, String address, String birth) {
        UserEditDialog editDialog = new UserEditDialog(phoneNumber, identity, realName, gender, address, birth);
        editDialog.setVisible(true);
        
        if (editDialog.isConfirmed()) {
            AdminUpdateDTO adminUpdateDTO = AdminUpdateDTO.builder()
                    .realName(editDialog.getRealName())
                    .identity(editDialog.getIdentity())
                    .phoneNumber(editDialog.getPhone())
                    .gender(editDialog.getGender())
                    .address(editDialog.getAddress())
                    .birth(editDialog.getBirth())
                    .build();
            
            try {
                Result result = userService.updateUser(adminUpdateDTO);
                if (result != null && result.isSuccess()) {
                    JOptionPane.showMessageDialog(table, "修改成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    refreshTable();
                } else {
                    JOptionPane.showMessageDialog(table, "修改失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(table, "网络错误，请重试！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private void handleDelete(String userId) {
        int confirmed = JOptionPane.showConfirmDialog(table, "确认要删除该用户吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirmed == JOptionPane.YES_OPTION) {
            try {
                Result result = userService.deleteUser(userId); // 使用 ID 号进行删除
                if (result != null && result.isSuccess()) {
                    JOptionPane.showMessageDialog(table, "删除成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    ((DefaultTableModel) table.getModel()).removeRow(row); // 从表格中移除行
                    refreshTable(); // 刷新表格以更新数据
                } else {
                    JOptionPane.showMessageDialog(table, "删除失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(table, "网络错误，请重试！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private void refreshTable() {
        ((UserArchiveQuery) SwingUtilities.getWindowAncestor(table)).freshTable(); // 刷新表格
    }
}
